//
//  HJWebViewController.m
//  KaiChat
//
//  Created by lx on 2023/10/17.
//

#import "HJWebViewController.h"
#import <WebKit/WebKit.h>


@interface HJWebViewController ()<WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;

@end

@implementation HJWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.backgroundColor = UIColor.whiteColor;
    
    self.webView = [WKWebView addToView:self.view];
    self.webView.navigationDelegate = self;
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.offset(KNavBarHight);
    }];
        
    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.progressView.frame = CGRectMake(0, 0, self.view.frame.size.width, 2); // 设置进度条的位置和高度
    self.progressView.progressTintColor = [UIColor tj_mainColor]; // 设置进度条的颜色
    self.progressView.trackTintColor = [UIColor clearColor]; // 设置进度条的底色
    [self.navigationBar addSubview:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(2);
    }];

    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];

    NSURL *url = [NSURL URLWithString:_url];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    self.progressView.hidden = YES;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webView) {
        CGFloat estimatedProgress = self.webView.estimatedProgress;
        // 更新进度条的值
        [self.progressView setProgress:estimatedProgress animated:YES];

        if (estimatedProgress >= 1.0) {
            dispatch_after_main_queue(1, ^{
                self.progressView.hidden = YES;
            });
        }
    }
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end

 
